<?php

namespace app\api\service\pay;

use app\api\model\activity\Goods as GoodsModel;

use app\api\service\coupon\MyCoupon;

use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;

use app\common\model\activity\ExtractorRel;
use app\common\model\Order;
use app\job\LuckyBagExtractor;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class ExtractorOrderPay extends PaySuccess
{

    private  $order_no = '';

    public function onSuccess(array $payment, int $payType)
    {
        Db::startTrans();
        try{
            // 商品更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            GoodsModel::update(['status' => 1,'sell_time' => time()], ['order_id' => $order->order_id]);
            $order->pay_status = PayStatus::SUCCESS;
            $order->trans_no = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time = time();
            $order->save();

            //关联隐藏款 更新
            $goods_ids = GoodsModel::where(['activity_id' => $order->activity_id,'order_id' => $order->order_id])->column('goods_id');
            $extractor_rels = ExtractorRel::where('activity_id',$order->activity_id)->whereIn('goods_id',$goods_ids)->select();
            if(!$extractor_rels->isEmpty()){
                foreach ($extractor_rels as $extractor_rel){
                    $extractor_rel->status = 1;
                    $extractor_rel->save();
                }
            }

            //核销优惠券
            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('抽盒机订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$order->order_id ?? 0,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }
            Db::commit();
            $this->order_no = $payment['order_no'];
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
        }
    }


    public function callSuccess()
    {
        // 用户订单
        Queue::push("app\\job\\LuckyBagExtractor", ['order_no' => $this->order_no], LuckyBagExtractor::QUEUE);
    }
}